# from email import message
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Content
import json
import os
from django.conf import settings
# from django.core import mail
from django.core.mail import send_mail

# Create your views here.

@csrf_exempt
def upload_picture(request):
    """
    图片上传接口，支持Element Plus上传组件
    """
    if request.method == 'POST':
        try:
            # 获取上传的文件
            uploaded_file = request.FILES.get('file')
            
            if not uploaded_file:
                return JsonResponse({
                    'success': False,
                    'message': '没有上传文件'
                }, status=400)
            
            # 验证文件类型
            allowed_types = ['image/jpeg', 'image/jpg', 'image/png']
            if uploaded_file.content_type not in allowed_types:
                return JsonResponse({
                    'success': False,
                    'message': '只允许上传JPG和PNG格式的图片'
                }, status=400)
            
            # 验证文件大小 (2MB)
            if uploaded_file.size > 2 * 1024 * 1024:
                return JsonResponse({
                    'success': False,
                    'message': '图片大小不能超过2MB'
                }, status=400)
            
            # 创建Content实例并保存文件
            content = Content()
            # 生成图片标题
            content.title = f"上传的图片_{uploaded_file.name}"
            # 保存图片到media目录
            content.picture = uploaded_file
            content.save()
            
            # 返回成功响应
            return JsonResponse({
                'success': True,
                'message': '图片上传成功',
                'data': {
                    'url': content.picture.url,
                    'filename': uploaded_file.name,
                    'size': uploaded_file.size
                }
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'上传失败: {str(e)}'
            }, status=500)
    
    return JsonResponse({
        'success': False,
        'message': '只支持POST请求'
    }, status=405)
        

# 邮件发送接口 - 简单直接版本
@csrf_exempt
def send_email(request):
    """
    邮件发送接口，就像图片上传一样简单
    """
    if request.method == 'POST':
        try:
            # 获取POST数据
            subject = request.POST.get('subject')
            message = request.POST.get('message')
            recipients = request.POST.get('recipients')
            
            # 如果没有表单数据，尝试JSON
            if not subject:
                try:
                    data = json.loads(request.body.decode('utf-8'))
                    subject = data.get('subject')
                    message = data.get('message')
                    recipients = data.get('recipients')
                except:
                    pass
            
            # 处理收件人格式 - 支持字符串和数组 这里不管前端是传进来数组还是字符串 都先洗一遍 后面再拼 因为不管前端检测再写得怎么好 其实都是可以绕过的 
            if isinstance(recipients, list):
                # 如果是数组 就先连接成字符串
                recipients = ','.join(recipients)  # 数组转字符串
            elif not isinstance(recipients, str):
                # 如果不是字符串也不是数组 就转成字符串
                recipients = str(recipients) if recipients else ''
            
            print(f"收到邮件请求 - 主题: {subject}, 收件人: {recipients} (类型: {type(recipients)})")
            print(f"邮件配置检查 - HOST: {settings.EMAIL_HOST}, PORT: {settings.EMAIL_PORT}, USER: {settings.EMAIL_HOST_USER}")
            
            # 简单验证
            if not subject:
                return JsonResponse({
                    'success': False,
                    'message': '请填写邮件主题'
                }, status=400)
                
            if not message:
                return JsonResponse({
                    'success': False,
                    'message': '请填写邮件内容'
                }, status=400)
                
            if not recipients:
                return JsonResponse({
                    'success': False,
                    'message': '请填写收件人邮箱'
                }, status=400)
            
            # 简单邮箱格式检查（支持多个邮箱）
            email_list = [email.strip() for email in recipients.split(',') if email.strip()]
            print(f"处理后的邮箱列表: {email_list}")
            for email in email_list:
                if '@' not in email or '.' not in email:
                    return JsonResponse({
                        'success': False,
                        'message': f'邮箱格式不正确: {email}'
                    }, status=400)
            
            # 发送邮件
            send_mail(
                subject=subject,
                message=message,
                from_email=settings.EMAIL_HOST_USER,
                recipient_list=email_list,  # 使用处理后的邮箱列表
                fail_silently=False
            )
            
            print("邮件发送成功！")
            
            return JsonResponse({
                'success': True,
                'message': '邮件发送成功！',
                'data': {
                    'subject': subject,
                    'recipients': email_list  # 返回处理后的邮箱列表
                }
            })
            
        except Exception as e:
            print(f"邮件发送失败: {e}")
            print(f"错误类型: {type(e)}")
            import traceback
            print(f"详细错误信息: {traceback.format_exc()}")
            return JsonResponse({
                'success': False,
                'message': f'邮件发送失败: {str(e)}'
            }, status=500)
    
    return JsonResponse({
        'success': False,
        'message': '只支持POST请求'
    }, status=405)

# 测试  访问此接口会触发一个报错  然后在自定义的中间件处理中向工作邮箱发送错误信息
@csrf_exempt
def  test_error(request):
    # 故意制造一个错误捕获
    undefined_variable.non_existent_attribute()  # 这里会触发未定义变量错误
    return JsonResponse({
        'success':True,
        'message':'测试错误成功 但是这条信息你永远不会被看到'
    })


